package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author 老李头儿
 * @since 2025-04-03
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redistemplate;
    private final BoundValueOperations<String, String> BoundValueOps;


    // 构造器注入redis, 注入redis的key(后续不需要每次都从redis中查)
    public ExchangeCodeServiceImpl(StringRedisTemplate redistemplate) {
        this.redistemplate = redistemplate;
        this.BoundValueOps = this.redistemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }


    /**
     * 异步生成兑换码
     *
     * @param coupon 优惠券
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    @Transactional
    public void asyncGenerateCode(Coupon coupon) {
        //获取发放数量
        Integer totalNum = coupon.getTotalNum();
        if (totalNum == null) {
            throw new BizIllegalException("优惠券发放数量为空");
        }
        //获取redis自增值
        Long increment = BoundValueOps.increment(totalNum);
        if (increment == null) {
            return;
        }
        int maxNum = increment.intValue();
        List<ExchangeCode> exchangeCodes = new ArrayList<>(totalNum);

        //循环生成兑换码
        for (int serialNum = maxNum - totalNum + 1; serialNum <= maxNum; serialNum++) {
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            ExchangeCode e = new ExchangeCode();
            e.setCode(code);
            e.setId(serialNum);
            e.setExchangeTargetId(coupon.getId());
            e.setExpiredTime(coupon.getIssueEndTime());
            exchangeCodes.add(e);
        }
        //保存到数据库
        saveBatch(exchangeCodes);

        //更新redis
        redistemplate.opsForZSet().add(COUPON_CODE_SERIAL_KEY, String.valueOf(maxNum), maxNum);



    }


    /**
    * @Description 分页查询兑换码
    * @Author 老李头儿
    * @Date 2025年04月04 15:58:03
    * @param query
    * @Return com.tianji.common.domain.dto.PageDTO<com.tianji.promotion.domain.po.ExchangeCode>
    **/
    @Override
    public PageDTO<ExchangeCode> pageCode(CodeQuery query) {
        //分页查询
        Page<ExchangeCode> page = this.lambdaQuery().eq(query.getStatus() != null, ExchangeCode::getStatus, query.getStatus())
                .eq(query.getCouponId() != null, ExchangeCode::getExchangeTargetId, query.getCouponId())
                .page(query.toMpPage());
        if (page != null) {
            return PageDTO.of(page);
        }

        return PageDTO.of(page);
    }
}
